-- ============================================
-- COURSE DE CHEVAUX - SNOUB CASINO
-- Nécessite : Advanced Computer + Advanced Monitor + Wired Modem
-- ============================================

local HORSES = {
    { name = "ZENH",   color = colors.red },
    { name = "SNOUB",  color = colors.lightBlue },
    { name = "WLODA",  color = colors.lime },
    { name = "DRAGUN", color = colors.purple },
}

local MISE = 1
local WIN_MULT = 3
local TICK = 0.24

local bank = dofile("client_solde.lua")

local mon = peripheral.find("monitor")
if not mon then
    error("Aucun monitor trouve ! Colle un Advanced Monitor a cote du computer.")
end

mon.setTextScale(0.5)
local prevTerm = term.redirect(mon)
local w, h = term.getSize()

local login = dofile("login.lua")
local player = login.authenticate("Qui parie sur la course ?")
local points = bank.getBalance(player)

local function centerText(y, text, textColor, bgColor)
    term.setBackgroundColor(bgColor or colors.black)
    term.setTextColor(textColor or colors.white)
    local x = math.floor((w - #text) / 2) + 1
    term.setCursorPos(x, y)
    term.write(text)
end

local function fillArea(x1, y1, x2, y2, bg)
    term.setBackgroundColor(bg)
    for y = y1, y2 do
        term.setCursorPos(x1, y)
        term.write(string.rep(" ", x2 - x1 + 1))
    end
end

-- === GEOMETRIE DE LA PISTE ===
local trackLeft = 3
local trackRight = w - 3
local trackTop = 6
local laneGap = 2

local function laneY(i)
    return trackTop + (i - 1) * laneGap
end

local function drawHeader(message, msgColor)
    fillArea(1, 1, w, trackTop - 1, colors.black)
    centerText(1, "=== SNOUB CASINO ===", colors.yellow)
    centerText(2, "COURSE DE CHEVAUX - " .. player, colors.white)
    centerText(3, "Points : " .. points, colors.lime)
    if message then
        centerText(4, message, msgColor or colors.white)
    end
end

local function drawTrackLines()
    for i = 1, #HORSES do
        local y = laneY(i)
        term.setBackgroundColor(colors.black)
        term.setTextColor(colors.gray)
        term.setCursorPos(trackLeft, y)
        term.write(string.rep(".", trackRight - trackLeft + 1))
    end
    term.setTextColor(colors.white)
    term.setCursorPos(trackRight + 1, trackTop - 1)
    for i = 1, #HORSES do
        term.setCursorPos(trackRight + 1, laneY(i))
        term.write("|")
    end
end

local function drawHorse(i, pos, trail, bounce, gallopFrame)
    local groundY = laneY(i)
    local h1 = HORSES[i]

    term.setBackgroundColor(colors.black)
    term.setTextColor(colors.gray)
    term.setCursorPos(trackLeft, groundY)
    term.write(string.rep(".", trackRight - trackLeft + 1))
    -- efface la ligne du rebond (au-dessus du sol) pour eviter les residus
    term.setCursorPos(trackLeft, groundY - 1)
    term.write(string.rep(" ", trackRight - trackLeft + 1))

    -- trainee de poussiere (positions precedentes, s'estompe)
    if trail then
        local fadeColors = { colors.gray, colors.lightGray }
        for t, oldPos in ipairs(trail) do
            local tx = math.min(trackRight, trackLeft + oldPos)
            term.setTextColor(fadeColors[t] or colors.gray)
            term.setCursorPos(tx, groundY)
            term.write("'")
        end
    end

    local x = math.min(trackRight, trackLeft + pos)
    local y = groundY + (bounce or 0)
    local frameChar = (gallopFrame == 0) and ">" or "~"
    term.setTextColor(h1.color)
    term.setCursorPos(x, y)
    term.write(frameChar .. h1.name:sub(1, 1))

    term.setTextColor(h1.color)
    term.setCursorPos(1, groundY)
    term.write(h1.name:sub(1, 4))
end

local function drawAllHorses(positions, trails, tick)
    local bounce = (tick % 2 == 0) and 0 or -1
    local gallopFrame = tick % 2
    for i = 1, #HORSES do
        drawHorse(i, positions[i], trails and trails[i], bounce, gallopFrame)
    end
    term.setTextColor(colors.white)
    for i = 1, #HORSES do
        term.setCursorPos(trackRight + 1, laneY(i))
        term.write("|")
    end
end

-- === FEU D'ARTIFICE POUR LE GAGNANT ===
local function celebrate(winnerIndex)
    local cx = trackRight
    local cy = laneY(winnerIndex)
    local sparkColors = { colors.yellow, colors.orange, colors.red, colors.lime, colors.white }
    local particles = {}
    for i = 1, 10 do
        particles[i] = {
            x = cx, y = cy,
            dx = math.random(-2, 2), dy = math.random(-1, 1),
            color = sparkColors[math.random(1, #sparkColors)],
        }
    end

    for tick = 1, 10 do
        for _, p in ipairs(particles) do
            term.setBackgroundColor(colors.black)
            term.setCursorPos(math.floor(p.x), math.floor(p.y))
            term.write(" ")
            p.x = p.x + p.dx * 0.6
            p.y = p.y + p.dy * 0.4
            if p.x >= trackLeft and p.x <= w and p.y >= 1 and p.y <= h then
                term.setTextColor(p.color)
                term.setCursorPos(math.floor(p.x), math.floor(p.y))
                term.write("*")
            end
        end
        sleep(0.08)
    end

    for _, p in ipairs(particles) do
        term.setBackgroundColor(colors.black)
        term.setCursorPos(math.floor(p.x), math.floor(p.y))
        term.write(" ")
    end
end

-- === UNE MANCHE ===
local function runRace(betHorse)
    local positions = {}
    local trails = {}
    for i = 1, #HORSES do
        positions[i] = 0
        trails[i] = {}
    end
    local trackLength = trackRight - trackLeft

    drawHeader("C'est parti !")
    drawAllHorses(positions, trails, 0)

    local winner = nil
    local tick = 0
    local timerId = os.startTimer(TICK)

    while not winner do
        local event, p1 = os.pullEvent()
        if event == "timer" and p1 == timerId then
            tick = tick + 1
            for i = 1, #HORSES do
                table.insert(trails[i], 1, positions[i])
                if #trails[i] > 2 then table.remove(trails[i]) end

                positions[i] = positions[i] + math.random(0, 3)
                if positions[i] >= trackLength and not winner then
                    winner = i
                end
            end
            drawAllHorses(positions, trails, tick)
            timerId = os.startTimer(TICK)
        end
    end

    celebrate(winner)
    return winner
end

local function playRound(betIndex)
    if points < MISE then
        drawHeader("PLUS ASSEZ DE POINTS !", colors.red)
        sleep(2)
        return
    end

    points = points - MISE
    local newBal1 = bank.addBalance(player, -MISE)
    points = newBal1 or points

    local winner = runRace(betIndex)
    local horseWinner = HORSES[winner]

    local gain = 0
    if winner == betIndex then
        gain = MISE * WIN_MULT
    end
    local newBal2 = bank.addBalance(player, gain)
    points = newBal2 or (points + gain)

    local msg, msgColor
    if gain > 0 then
        msg, msgColor = horseWinner.name .. " gagne ! Tu remportes +" .. gain, colors.lime
    else
        msg, msgColor = horseWinner.name .. " gagne... perdu !", colors.red
    end

    drawHeader(msg, msgColor)
    sleep(2.5)
end

-- === ECRAN DE MISE ===
local buttons = {}

local function drawIdle()
    term.setBackgroundColor(colors.black)
    term.clear()
    drawHeader()
    drawTrackLines()
    for i = 1, #HORSES do
        term.setTextColor(HORSES[i].color)
        term.setCursorPos(1, laneY(i))
        term.write(HORSES[i].name:sub(1, 4))
    end

    centerText(trackTop + (#HORSES - 1) * laneGap + 2,
        "Choisis un cheval (mise " .. MISE .. " point, x" .. WIN_MULT .. " si gagnant)", colors.lightGray)

    buttons = {}
    local startY = trackTop + (#HORSES - 1) * laneGap + 4
    local btnW = math.floor(w / #HORSES)
    for i, horse in ipairs(HORSES) do
        local x1 = (i - 1) * btnW + 1
        local x2 = x1 + btnW - 1
        term.setBackgroundColor(horse.color)
        term.setTextColor(colors.black)
        for x = x1, x2 do
            term.setCursorPos(x, startY)
            term.write(" ")
        end
        local lx = x1 + math.floor((btnW - #horse.name) / 2)
        term.setCursorPos(lx, startY)
        term.write(horse.name)
        buttons[i] = { x1 = x1, x2 = x2, y = startY }
    end
end

-- === PROGRAMME PRINCIPAL ===
drawIdle()

while true do
    local event, side, x, y = os.pullEvent("monitor_touch")
    for i, btn in ipairs(buttons) do
        if x >= btn.x1 and x <= btn.x2 and y == btn.y then
            playRound(i)
            drawIdle()
            break
        end
    end
end
